package com.func.domain.strategy.service.rule.tree.impl;

import com.func.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.func.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @version 1.0
 * @className RuleLockLogicTreeNode
 * @description 规则树节点-计数锁规则
 * @author: func
 * @date 2025/2/28 21:18
 */

@Component("rule_lock")
@Slf4j
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository strategyRepository;
    /**
     * 简单实现, 直接返回通过
     *
     * @param userId
     * @param strategyId
     * @param awardId    前面抽奖得到的奖品Id
     * @param ruleValue
     * @return
     */
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);

        long raffleCount = 0L;
        try {
            raffleCount = Long.parseLong(ruleValue);
        } catch (Exception e) {
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue" + ruleValue + "配置不正确");
        }

        // 查询用户抽奖次数 - 当天的: 策略ID:活动ID 1: 的配置, 可以直接使用 strategyId 查询
        Integer userRaffleCount = strategyRepository.queryTodayUserRaffleCount(userId, strategyId);

        // 用户抽奖次数大于等于规定次数
        if (userRaffleCount >= raffleCount) {
            log.info("规则过滤-次数锁-放行 userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
        }
        log.info("规则过滤-次数锁-接管 userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .build())
                .build();
    }
}
